package handler

import (
	"litetalk/api/form"
	"litetalk/proto"

	"github.com/gin-gonic/gin"
)

func NormalGroupList(c *gin.Context) {
	// 1 使用token获取用户信息
	var form form.FormCheckAuth
	if err := c.ShouldBindJSON(&form); err != nil {
		FailWithMsg(c, err.Error())
		return
	}

	id, err := CheckAuth(form.AuthToken)
	if id == 0 || err != nil {
		FailWithMsg(c, err.Error())
		return
	}

	// 2 RPC调用获取所有组信息
	args := &proto.IMNormalGroupListReq{}
	reply := &proto.IMNormalGroupListRes{}
	if err := logicRpc.NormalGroupList(args, reply); err != nil {
		FailWithMsg(c, err.Error())
	} else {
		SuccessWithMsg(c, "ok", reply.GroupIdList)
	}
}

func GroupsInfo(c *gin.Context) {
	var form form.FormCheckAuth
	if err := c.ShouldBindJSON(&form); err != nil {
		FailWithMsg(c, err.Error())
		return
	}

	// 1 检验用户许可
	{
		args := &proto.CheckAuthReq{}
		reply := &proto.CheckAuthRep{}
		if err := logicRpc.CheckAuth(args, reply); err != nil {
			FailWithMsg(c, err.Error())
			return
		}
	}

	// 2 RPC调用
	args := &proto.IMGroupInfoListReq{}
	reply := &proto.IMGroupInfoListRes{}
	if err := logicRpc.GroupsInfo(args, reply); err != nil {
		FailWithMsg(c, err.Error())
		return
	}

	SuccessWithMsg(c, nil, reply.GroupInfoList)
}

func CreateGroup(c *gin.Context) {
	var form form.FormCreateGroup
	if err := c.ShouldBindJSON(&form); err != nil {
		FailWithMsg(c, err.Error())
		return
	}

	var userId uint
	// 1 获取用户信息
	{
		args := &proto.CheckAuthReq{}
		reply := &proto.CheckAuthRep{}
		if err := logicRpc.CheckAuth(args, reply); err != nil {
			FailWithMsg(c, err.Error())
			return
		}
		userId = reply.UserId
	}

	var groupId uint
	// 2 RPC调用
	args := &proto.IMGroupCreateReq{
		UserId:       userId,
		GroupName:    form.Name,
		MemberIdList: form.Members,
	}
	reply := &proto.IMGroupCreateRes{}
	if err := logicRpc.CreateGroup(args, reply); err != nil {
		FailWithMsg(c, err.Error())
		return
	}
	groupId = reply.GroupId
	SuccessWithMsg(c, "ok", groupId)
}

func GroupChangeMember(c *gin.Context) {
	var form form.FormGroupChange
	if err := c.ShouldBindJSON(&form); err != nil {
		FailWithMsg(c, err.Error())
		return
	}
	var userId uint
	// 1 获取用户信息
	{
		args := &proto.CheckAuthReq{}
		reply := &proto.CheckAuthRep{}
		if err := logicRpc.CheckAuth(args, reply); err != nil {
			FailWithMsg(c, err.Error())
			return
		}
		userId = reply.UserId
	}
	args := &proto.IMGroupChangeMemberReq{
		UserId:       userId,
		GroupId:      form.GroupId,
		ChangeType:   form.ChangeType,
		MemberIdList: form.MemberIds,
	}
	reply := &proto.IMGroupChangeMemberRes{}
	if err := logicRpc.GroupChangeMember(args, reply); err != nil {
		FailWithMsg(c, err)
		return
	}
	SuccessWithMsg(c, nil, nil)
}
